import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../common/routes.dart';
import '../common/utils.dart';
import '../model/community_video_model.dart';

class TopicListView extends StatefulWidget {
  const TopicListView({super.key});

  @override
  State<TopicListView> createState() => _TopicListViewState();
}

class _TopicListViewState extends State<TopicListView> with AutomaticKeepAliveClientMixin {
  final ScrollController _scrollController = ScrollController();
  final List<IssueList> _videoList = [];
  bool _isLoadingMore = false;
  bool _isLoadingData = true;
  bool _hasMore = true;
  var _url = "https://baobab.kaiyanapp.com/api/v3/specialTopics";

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent && !_isLoadingMore) {
        _loadMore();
      }
    });

    loadData();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  _loadMore() async {
    setState(() {
      _isLoadingMore = true;
    });
    await loadData();
  }

  loadData() async {
    Dio dio = Dio();
    final response = await dio.get(_url);
    var model = CommunityVideoModel.fromJson(response.data);
    var count = model.count ?? 0;
    setState(() {
      _isLoadingData = false;
      _isLoadingMore = false;
      if (count > 0) {
        _url = model.nextPageUrl ?? '';
        _videoList.addAll(model.itemList ?? []);
      } else {
        _hasMore = false;
      }
    });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (_isLoadingData) {
      return Center(
        child: Container(
          margin: const EdgeInsets.all(8.0),
          width: 64.0,
          height: 64.0,
          child: const CircularProgressIndicator(),
        ),
      );
    }
    return ListView.builder(
      controller: _scrollController,
      itemCount: _videoList.length + 1,
      itemBuilder: (context, index) {
        if (index == _videoList.length) {
          if (_isLoadingMore) {
            // Show loading indicator
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(child: CircularProgressIndicator()),
            );
          } else if (!_hasMore) {
            // No more data
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(child: Text('没有更多数据了')),
            );
          } else {
            return SizedBox.shrink();
          }
        }

        final item = _videoList[index];
        var imageUrl = item.data?.image ?? '';
        imageUrl = convertImageUrl(imageUrl);

        return GestureDetector(
          child: Container(
            color: Colors.white,
            margin: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: CachedNetworkImage(
                width: double.infinity,
                height: 200,
                fadeInDuration: const Duration(seconds: 0),
                fadeOutDuration: const Duration(seconds: 0),
                fit: BoxFit.cover,
                imageUrl: imageUrl,
                placeholder: (context, url) {
                  return Image.asset(
                    "assets/images/placeholder.png",
                    fit: BoxFit.cover,
                  );
                },
              ),
            ),
          ),
          onTap: () {
            Get.toNamed(Routes.VIDEO_TOPIC_DETAIL, arguments: {"id": item.data?.id});
          },
        );
      },
    );
  }
}
